package io.coderyeah.ymcc.quartz;

import com.alibaba.fastjson2.JSON;
import io.coderyeah.ymcc.dto.GoodsDTO;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.List;
import java.util.Set;

/**
 * @author lqs
 * @date 2022/11/6 11:05
 */
@Slf4j
public class QuartzCartJob extends QuartzJobBean {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        // 每隔10秒执行一次
        // 获取redis中所有的商品
        Set<Object> keys = redisTemplate.keys(("cache:goods:*"));// 获取所有key
        assert keys != null;
        keys.forEach(key -> {
            // 遍历每一个key 获取当前key的所有值
            List<Object> values = redisTemplate.opsForHash().values(key);
            List<GoodsDTO> goodsDTOS = JSON.parseArray(JSON.toJSONString(values), GoodsDTO.class);
            // 遍历货品
            goodsDTOS.forEach(goodsDTO -> {
                // 判断存储时间是否大于一分钟
                if (System.currentTimeMillis() - goodsDTO.getTime() > 1000 * 60) {
                    // 删除此物品
                    redisTemplate.opsForHash().delete(key, goodsDTO.getId().toString());
                    log.info("定时删除成功");
                }
            });
        });
        System.out.println(keys);

        String userName = (String) context.getJobDetail().getJobDataMap().get("userName");
        System.out.println("userName:" + userName);
    }
}
